package org.gp.demo.timer.job;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class CheckEmailJob implements Job {
	String mailHost = "http://mail.163.com";//"mail.topsuntech.com.cn";
	String username = "gaoping0730@163.com";//"gaoping@topsuntech.com";
	String password = "^@gao1103";

	// Default Constructor
	public CheckEmailJob() {
		super();
	}

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		checkMail();
	}

	protected void checkMail() {

		// Get session
		Session session = null;

		try {

			// Get system properties
			Properties props = System.getProperties();

			session = Session.getDefaultInstance(props, null);
			// Get the store
			Store store = session.getStore("pop3");
			store.connect(mailHost, username, password);

			// Get folder
			Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_ONLY);

			// Get directory
			Message message[] = folder.getMessages();
			int numOfMsgs = message.length;

			if (numOfMsgs > 0) {
				for (int i = 0, n = numOfMsgs; i < n; i++) {
					System.out.println("(" + i + "  of " + numOfMsgs + "): "
							+ message[i].getFrom()[0] + "\t"
							+ message[i].getSubject());
				}
			} else {
				System.out.println("No Messages for user");
			}

			// Close connection
			folder.close(false);
			store.close();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		CheckEmailJob job = new CheckEmailJob();
		job.checkMail();
	}
}
